#include <iostream>
using std::cout;
using std::endl;

class Singleton
{
public:
    static Singleton * getInstance(){
        //当多个线程同时进入if语句时
        //会造成Singleton对象被创建多份
        //但是最终只有一个Singleton对象的地址
        //被_pInstance所保存
        //那么也只有这一个Singleton对象能够被回收
        //其他的都泄露了
        if(nullptr == _pInstance){
            atexit(destroy);
            _pInstance = new Singleton(1,2);
        }
        return _pInstance;
    }

    void init(int x,int y){
        _ix = x;
        _iy = y;
    }

   
    void print(){
        cout << "(" << _ix
            << "," << _iy
            << ")" << endl;
    }
private:
    Singleton() = default;
    Singleton(int x,int y)
    : _ix(x)
    , _iy(y)
    {
        cout << "Singleton(int,int)" << endl;
    }

    ~Singleton(){
        cout << "~Singleton()" << endl;
    }
    
    static void destroy(){
        if(_pInstance){
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    Singleton(const Singleton & rhs) = delete;
    Singleton & operator=(const Singleton & rhs) = delete;
private:
    int _ix;
    int _iy;
    static Singleton * _pInstance;
};
//饱汉式（懒汉式）
//懒加载，等到人为使用Singleton对象时才创建
/* Singleton * Singleton::_pInstance = nullptr; */

//饿汉式
//即使不使用Singleton对象，也在一开始就创建
Singleton * Singleton::_pInstance = Singleton::getInstance();


void test0(){
    Singleton::getInstance()->init(3,4);
    Singleton::getInstance()->print();
    Singleton::getInstance()->init(8,9);
    Singleton::getInstance()->print();
    /* Singleton::destroy(); */
    Singleton::getInstance()->init(8,9);
    Singleton::getInstance()->print();
}

int main(void){
    test0();
    return 0;
}
